"""
监控报告流程

定义系统监控、性能报告和合规报告的工作流程。
"""

from typing import Dict, List, Any, Optional
from datetime import datetime, timedelta

from .workflow_types import (
    WorkflowDefinition,
    WorkflowNode,
    WorkflowEdge,
    WorkflowType,
    NodeType,
    EdgeType
)


class MonitoringReportingFlow:
    """
    监控报告流程构建器
    
    负责构建监控和报告相关的工作流定义。
    """
    
    @staticmethod
    def create_real_time_monitoring_flow() -> WorkflowDefinition:
        """
        创建实时监控流程
        
        Returns:
            实时监控工作流定义
        """
        workflow = WorkflowDefinition(
            id="real_time_monitoring",
            name="实时监控流程",
            type=WorkflowType.MONITORING_REPORTING,
            description="实时监控系统状态、投资组合和风险指标",
            timeout=timedelta(hours=24)  # 持续运行
        )
        
        # 开始节点
        start_node = WorkflowNode(
            node_id="start",
            name="开始",
            node_type=NodeType.START,
            description="实时监控流程开始"
        )
        workflow.add_node(start_node)
        workflow.start_node_id = "start"
        
        # 数据收集
        data_collection = WorkflowNode(
            node_id="data_collection",
            name="数据收集",
            node_type=NodeType.TASK,
            description="收集实时市场数据和系统状态",
            executor="data_collector",
            timeout=timedelta(seconds=30),
            parameters={
                "data_sources": [
                    "market_data_feed",
                    "portfolio_positions",
                    "system_metrics",
                    "trading_activity",
                    "risk_metrics"
                ],
                "collection_frequency": 5,  # seconds
                "data_validation": True,
                "error_handling": "continue_on_error"
            }
        )
        workflow.add_node(data_collection)
        
        # 指标计算
        metrics_calculation = WorkflowNode(
            node_id="metrics_calculation",
            name="指标计算",
            node_type=NodeType.TASK,
            description="计算关键性能和风险指标",
            executor="metrics_calculator",
            parallel_branches=["portfolio_metrics", "risk_metrics", "system_metrics"],
            parameters={
                "calculation_types": [
                    "portfolio_value",
                    "pnl_calculation",
                    "var_calculation",
                    "exposure_analysis",
                    "performance_attribution"
                ],
                "real_time_updates": True
            }
        )
        workflow.add_node(metrics_calculation)
        
        # 投资组合指标
        portfolio_metrics = WorkflowNode(
            node_id="portfolio_metrics",
            name="投资组合指标",
            node_type=NodeType.TASK,
            description="计算投资组合相关指标",
            executor="portfolio_metrics_calculator",
            parameters={
                "metrics": [
                    "total_value",
                    "daily_pnl",
                    "unrealized_pnl",
                    "sector_allocation",
                    "asset_allocation",
                    "concentration_risk"
                ]
            }
        )
        workflow.add_node(portfolio_metrics)
        
        # 风险指标
        risk_metrics = WorkflowNode(
            node_id="risk_metrics",
            name="风险指标",
            node_type=NodeType.TASK,
            description="计算风险相关指标",
            executor="risk_metrics_calculator",
            parameters={
                "risk_measures": [
                    "value_at_risk",
                    "expected_shortfall",
                    "maximum_drawdown",
                    "volatility",
                    "beta",
                    "correlation_matrix"
                ]
            }
        )
        workflow.add_node(risk_metrics)
        
        # 系统指标
        system_metrics = WorkflowNode(
            node_id="system_metrics",
            name="系统指标",
            node_type=NodeType.TASK,
            description="计算系统性能指标",
            executor="system_metrics_calculator",
            parameters={
                "system_measures": [
                    "cpu_usage",
                    "memory_usage",
                    "disk_usage",
                    "network_latency",
                    "database_performance",
                    "api_response_time"
                ]
            }
        )
        workflow.add_node(system_metrics)
        
        # 阈值检查
        threshold_check = WorkflowNode(
            node_id="threshold_check",
            name="阈值检查",
            node_type=NodeType.DECISION,
            description="检查指标是否超过预设阈值",
            conditions=[
                {
                    "name": "normal_status",
                    "expression": "all(metric['status'] == 'normal' for metric in all_metrics)"
                },
                {
                    "name": "warning_triggered",
                    "expression": "any(metric['status'] == 'warning' for metric in all_metrics)"
                },
                {
                    "name": "alert_triggered",
                    "expression": "any(metric['status'] == 'alert' for metric in all_metrics)"
                },
                {
                    "name": "critical_triggered",
                    "expression": "any(metric['status'] == 'critical' for metric in all_metrics)"
                }
            ]
        )
        workflow.add_node(threshold_check)
        
        # 告警处理
        alert_handling = WorkflowNode(
            node_id="alert_handling",
            name="告警处理",
            node_type=NodeType.TASK,
            description="处理告警和通知",
            executor="alert_handler",
            parameters={
                "alert_channels": [
                    "email",
                    "sms",
                    "slack",
                    "dashboard",
                    "mobile_push"
                ],
                "escalation_rules": {
                    "warning": ["email", "dashboard"],
                    "alert": ["email", "sms", "dashboard"],
                    "critical": ["email", "sms", "slack", "mobile_push", "dashboard"]
                },
                "notification_templates": "from_config"
            }
        )
        workflow.add_node(alert_handling)
        
        # 数据存储
        data_storage = WorkflowNode(
            node_id="data_storage",
            name="数据存储",
            node_type=NodeType.TASK,
            description="存储监控数据和指标",
            executor="data_storer",
            parameters={
                "storage_targets": [
                    "timeseries_database",
                    "metrics_cache",
                    "alert_log",
                    "audit_trail"
                ],
                "retention_policies": {
                    "real_time_data": "7_days",
                    "hourly_aggregates": "30_days",
                    "daily_aggregates": "1_year",
                    "alerts": "2_years"
                }
            }
        )
        workflow.add_node(data_storage)
        
        # 仪表板更新
        dashboard_update = WorkflowNode(
            node_id="dashboard_update",
            name="仪表板更新",
            node_type=NodeType.TASK,
            description="更新实时监控仪表板",
            executor="dashboard_updater",
            parameters={
                "dashboard_components": [
                    "portfolio_overview",
                    "risk_dashboard",
                    "system_status",
                    "trading_activity",
                    "alert_panel"
                ],
                "update_frequency": "real_time",
                "auto_refresh": True
            }
        )
        workflow.add_node(dashboard_update)
        
        # 监控循环
        monitoring_loop = WorkflowNode(
            node_id="monitoring_loop",
            name="监控循环",
            node_type=NodeType.LOOP,
            description="持续监控循环",
            loop_condition="monitoring_active == True",
            max_iterations=999999,  # 近似无限循环
            parameters={
                "loop_interval": 5,  # seconds
                "health_check": True
            }
        )
        workflow.add_node(monitoring_loop)
        
        # 结束节点
        end_node = WorkflowNode(
            node_id="end",
            name="结束",
            node_type=NodeType.END,
            description="监控流程结束"
        )
        workflow.add_node(end_node)
        workflow.end_node_ids = ["end"]
        
        # 添加边
        edges = [
            # 主流程
            WorkflowEdge("edge_1", "start", "monitoring_loop", EdgeType.SEQUENCE),
            WorkflowEdge("edge_2", "monitoring_loop", "data_collection", EdgeType.SEQUENCE),
            WorkflowEdge("edge_3", "data_collection", "metrics_calculation", EdgeType.SEQUENCE),
            WorkflowEdge("edge_4", "metrics_calculation", "threshold_check", EdgeType.SEQUENCE),
            
            # 阈值检查分支
            WorkflowEdge("edge_5", "threshold_check", "data_storage", EdgeType.CONDITION,
                        condition="threshold_check_result['normal_status']"),
            WorkflowEdge("edge_6", "threshold_check", "alert_handling", EdgeType.CONDITION,
                        condition="threshold_check_result['warning_triggered'] or threshold_check_result['alert_triggered'] or threshold_check_result['critical_triggered']"),
            
            # 告警处理后存储
            WorkflowEdge("edge_7", "alert_handling", "data_storage", EdgeType.SEQUENCE),
            
            # 仪表板更新
            WorkflowEdge("edge_8", "data_storage", "dashboard_update", EdgeType.SEQUENCE),
            
            # 循环回到监控开始
            WorkflowEdge("edge_9", "dashboard_update", "monitoring_loop", EdgeType.SEQUENCE),
            
            # 结束条件
            WorkflowEdge("edge_10", "monitoring_loop", "end", EdgeType.CONDITION,
                        condition="monitoring_active == False")
        ]
        
        for edge in edges:
            workflow.add_edge(edge)
        
        # 设置输入输出模式
        workflow.input_schema = {
            "type": "object",
            "properties": {
                "monitoring_config": {"type": "object"},
                "alert_thresholds": {"type": "object"},
                "dashboard_settings": {"type": "object"}
            }
        }
        
        workflow.output_schema = {
            "type": "object",
            "properties": {
                "monitoring_status": {"type": "string"},
                "current_metrics": {"type": "object"},
                "active_alerts": {"type": "array"},
                "system_health": {"type": "object"}
            }
        }
        
        return workflow
    
    @staticmethod
    def create_daily_report_flow() -> WorkflowDefinition:
        """
        创建日报生成流程
        
        Returns:
            日报生成工作流定义
        """
        workflow = WorkflowDefinition(
            id="daily_report",
            name="日报生成流程",
            type=WorkflowType.MONITORING_REPORTING,
            description="生成每日投资组合和风险报告",
            timeout=timedelta(hours=1)
        )
        
        # 开始节点
        start_node = WorkflowNode(
            node_id="start",
            name="开始",
            node_type=NodeType.START
        )
        workflow.add_node(start_node)
        workflow.start_node_id = "start"
        
        # 数据汇总
        data_aggregation = WorkflowNode(
            node_id="data_aggregation",
            name="数据汇总",
            node_type=NodeType.TASK,
            description="汇总当日交易和持仓数据",
            executor="data_aggregator",
            parameters={
                "aggregation_period": "1_day",
                "data_sources": [
                    "trading_records",
                    "position_snapshots",
                    "market_data",
                    "pnl_records"
                ]
            }
        )
        workflow.add_node(data_aggregation)
        
        # 性能分析
        performance_analysis = WorkflowNode(
            node_id="performance_analysis",
            name="性能分析",
            node_type=NodeType.TASK,
            description="分析投资组合性能",
            executor="performance_analyzer",
            parameters={
                "analysis_components": [
                    "daily_return",
                    "cumulative_return",
                    "benchmark_comparison",
                    "attribution_analysis",
                    "sector_performance"
                ]
            }
        )
        workflow.add_node(performance_analysis)
        
        # 风险分析
        risk_analysis = WorkflowNode(
            node_id="risk_analysis",
            name="风险分析",
            node_type=NodeType.TASK,
            description="分析风险指标和暴露",
            executor="risk_analyzer",
            parameters={
                "risk_components": [
                    "var_analysis",
                    "stress_testing",
                    "concentration_analysis",
                    "correlation_analysis"
                ]
            }
        )
        workflow.add_node(risk_analysis)
        
        # 交易分析
        trading_analysis = WorkflowNode(
            node_id="trading_analysis",
            name="交易分析",
            node_type=NodeType.TASK,
            description="分析交易活动和执行质量",
            executor="trading_analyzer",
            parameters={
                "trading_metrics": [
                    "execution_cost",
                    "market_impact",
                    "fill_rate",
                    "timing_analysis"
                ]
            }
        )
        workflow.add_node(trading_analysis)
        
        # 报告生成
        report_generation = WorkflowNode(
            node_id="report_generation",
            name="报告生成",
            node_type=NodeType.TASK,
            description="生成格式化的日报",
            executor="report_generator",
            parameters={
                "report_format": "pdf",
                "template": "daily_report_template",
                "include_charts": True,
                "language": "chinese"
            }
        )
        workflow.add_node(report_generation)
        
        # 报告分发
        report_distribution = WorkflowNode(
            node_id="report_distribution",
            name="报告分发",
            node_type=NodeType.TASK,
            description="分发日报给相关人员",
            executor="report_distributor",
            parameters={
                "distribution_list": [
                    "portfolio_managers",
                    "risk_managers",
                    "senior_management"
                ],
                "delivery_methods": ["email", "shared_folder"]
            }
        )
        workflow.add_node(report_distribution)
        
        # 结束节点
        end_node = WorkflowNode(
            node_id="end",
            name="结束",
            node_type=NodeType.END
        )
        workflow.add_node(end_node)
        workflow.end_node_ids = ["end"]
        
        # 添加边
        edges = [
            WorkflowEdge("edge_1", "start", "data_aggregation", EdgeType.SEQUENCE),
            WorkflowEdge("edge_2", "data_aggregation", "performance_analysis", EdgeType.PARALLEL),
            WorkflowEdge("edge_3", "data_aggregation", "risk_analysis", EdgeType.PARALLEL),
            WorkflowEdge("edge_4", "data_aggregation", "trading_analysis", EdgeType.PARALLEL),
            WorkflowEdge("edge_5", "performance_analysis", "report_generation", EdgeType.SEQUENCE),
            WorkflowEdge("edge_6", "risk_analysis", "report_generation", EdgeType.SEQUENCE),
            WorkflowEdge("edge_7", "trading_analysis", "report_generation", EdgeType.SEQUENCE),
            WorkflowEdge("edge_8", "report_generation", "report_distribution", EdgeType.SEQUENCE),
            WorkflowEdge("edge_9", "report_distribution", "end", EdgeType.SEQUENCE),
        ]
        
        for edge in edges:
            workflow.add_edge(edge)
        
        return workflow
    
    @staticmethod
    def create_compliance_report_flow() -> WorkflowDefinition:
        """
        创建合规报告流程
        
        Returns:
            合规报告工作流定义
        """
        workflow = WorkflowDefinition(
            id="compliance_report",
            name="合规报告流程",
            type=WorkflowType.MONITORING_REPORTING,
            description="生成监管合规和内控报告",
            timeout=timedelta(hours=2)
        )
        
        # 开始节点
        start_node = WorkflowNode(
            node_id="start",
            name="开始",
            node_type=NodeType.START
        )
        workflow.add_node(start_node)
        workflow.start_node_id = "start"
        
        # 合规检查
        compliance_check = WorkflowNode(
            node_id="compliance_check",
            name="合规检查",
            node_type=NodeType.TASK,
            description="执行各项合规检查",
            executor="compliance_checker",
            parameters={
                "compliance_rules": [
                    "position_limits",
                    "concentration_limits",
                    "investment_restrictions",
                    "trading_limits",
                    "disclosure_requirements"
                ]
            }
        )
        workflow.add_node(compliance_check)
        
        # 违规检测
        violation_detection = WorkflowNode(
            node_id="violation_detection",
            name="违规检测",
            node_type=NodeType.TASK,
            description="检测潜在的合规违规",
            executor="violation_detector",
            parameters={
                "detection_algorithms": [
                    "limit_breach_detection",
                    "unusual_trading_pattern",
                    "conflict_of_interest",
                    "insider_trading_detection"
                ]
            }
        )
        workflow.add_node(violation_detection)
        
        # 合规报告生成
        compliance_report_generation = WorkflowNode(
            node_id="compliance_report_generation",
            name="合规报告生成",
            node_type=NodeType.TASK,
            description="生成合规报告",
            executor="compliance_report_generator",
            parameters={
                "report_types": [
                    "regulatory_filing",
                    "internal_audit",
                    "risk_committee_report",
                    "board_report"
                ]
            }
        )
        workflow.add_node(compliance_report_generation)
        
        # 结束节点
        end_node = WorkflowNode(
            node_id="end",
            name="结束",
            node_type=NodeType.END
        )
        workflow.add_node(end_node)
        workflow.end_node_ids = ["end"]
        
        # 添加边
        edges = [
            WorkflowEdge("edge_1", "start", "compliance_check", EdgeType.SEQUENCE),
            WorkflowEdge("edge_2", "compliance_check", "violation_detection", EdgeType.SEQUENCE),
            WorkflowEdge("edge_3", "violation_detection", "compliance_report_generation", EdgeType.SEQUENCE),
            WorkflowEdge("edge_4", "compliance_report_generation", "end", EdgeType.SEQUENCE),
        ]
        
        for edge in edges:
            workflow.add_edge(edge)
        
        return workflow
    
    @staticmethod
    def create_performance_attribution_flow() -> WorkflowDefinition:
        """
        创建业绩归因分析流程
        
        Returns:
            业绩归因分析工作流定义
        """
        workflow = WorkflowDefinition(
            id="performance_attribution",
            name="业绩归因分析流程",
            type=WorkflowType.MONITORING_REPORTING,
            description="详细的投资组合业绩归因分析",
            timeout=timedelta(hours=1)
        )
        
        # 开始节点
        start_node = WorkflowNode(
            node_id="start",
            name="开始",
            node_type=NodeType.START
        )
        workflow.add_node(start_node)
        workflow.start_node_id = "start"
        
        # 收益分解
        return_decomposition = WorkflowNode(
            node_id="return_decomposition",
            name="收益分解",
            node_type=NodeType.TASK,
            description="分解投资组合收益来源",
            executor="return_decomposer",
            parameters={
                "decomposition_methods": [
                    "brinson_attribution",
                    "factor_attribution",
                    "sector_attribution",
                    "security_selection"
                ]
            }
        )
        workflow.add_node(return_decomposition)
        
        # 风险归因
        risk_attribution = WorkflowNode(
            node_id="risk_attribution",
            name="风险归因",
            node_type=NodeType.TASK,
            description="分析风险来源和贡献",
            executor="risk_attributor",
            parameters={
                "risk_models": [
                    "factor_risk_model",
                    "statistical_risk_model",
                    "fundamental_risk_model"
                ]
            }
        )
        workflow.add_node(risk_attribution)
        
        # 归因报告
        attribution_report = WorkflowNode(
            node_id="attribution_report",
            name="归因报告",
            node_type=NodeType.TASK,
            description="生成业绩归因报告",
            executor="attribution_reporter",
            parameters={
                "report_components": [
                    "attribution_summary",
                    "detailed_breakdown",
                    "historical_comparison",
                    "peer_comparison"
                ]
            }
        )
        workflow.add_node(attribution_report)
        
        # 结束节点
        end_node = WorkflowNode(
            node_id="end",
            name="结束",
            node_type=NodeType.END
        )
        workflow.add_node(end_node)
        workflow.end_node_ids = ["end"]
        
        # 添加边
        edges = [
            WorkflowEdge("edge_1", "start", "return_decomposition", EdgeType.PARALLEL),
            WorkflowEdge("edge_2", "start", "risk_attribution", EdgeType.PARALLEL),
            WorkflowEdge("edge_3", "return_decomposition", "attribution_report", EdgeType.SEQUENCE),
            WorkflowEdge("edge_4", "risk_attribution", "attribution_report", EdgeType.SEQUENCE),
            WorkflowEdge("edge_5", "attribution_report", "end", EdgeType.SEQUENCE),
        ]
        
        for edge in edges:
            workflow.add_edge(edge)
        
        return workflow